import axios from 'axios'
import store from '@/store/index'
import router from '@/router'
import { Message } from 'element-ui'

function Serve(name, baseURL) {
  this[name] = axios.create({
    baseURL: baseURL, // url = base url + request url
    timeout: 5000
  })

  this[name].interceptors.request.use(
    function(config) {
      if (store.getters.token) {
        if ((Date.now() - store.getters.tokenTime) > 1000 * 60 * 60 * 2) {
          store.commit('navigation/delAllTabList')
          store.commit('user/exit')
          router.push('/login')
          return Promise.reject('token失效咯')
        }
      }
      return config
    },
    function(error) {
      return Promise.reject(error)
    }

  )

  this[name].interceptors.response.use(
    function(config) {
      return config.data
    },
    function(error) {
      console.log(error)
      if (!error.response) {
        Message.error(error)
      } else {
        Message.error(error.response.data)
      }
      return Promise.reject(error.response)
    }
  )
}

export const { requestIPS } = new Serve('requestIPS', process.env.VUE_APP_BASE_IPS)
export const { requestAPI } = new Serve('requestAPI', process.env.VUE_APP_BASE_API)
